package com.ww.common;


import org.springframework.util.StringUtils;

import java.util.function.Supplier;

public class ServiceException extends RuntimeException implements Supplier<ServiceException> {

    public static final String CODE_EXCEPTION = "200";

    private String errcode;

    private String errmsg;

    public ServiceException(String message) {
        super();
        init(null, message, null);
    }

    public ServiceException(String code, String message) {
        super(message);
        init(code, message, null);
    }

    public ServiceException(String code, String message, Throwable cause) {
        super(message, cause);
        init(code, message, cause);
    }

    public ServiceException(Throwable cause) {
        super(cause);
        init(null, null, cause);
    }

    public String getCode() {
        return errcode;
    }

    @Override
    public String getMessage() {
        return errmsg;
    }

    private void init(String code, String message, Throwable cause) {
        this.errcode = StringUtils.isEmpty(code) ? CODE_EXCEPTION : code;
        StringBuilder msg = new StringBuilder();
        if (!StringUtils.isEmpty(message)) {
            msg.append(message);
        }
        if (cause != null && !StringUtils.isEmpty(cause.getMessage())) {
            if (!StringUtils.isEmpty(message))
                msg.append(" : ");
            msg.append(cause.getMessage());
        }
        this.errmsg = msg.toString();
    }

    @Override
    public ServiceException get() {
        return this;
    }
}
